import Vue from "vue";
import VueRouter from "vue-router";
import Login from "../views/login.vue";
import Home from "../views/Home.vue";
import Welcome from "../views/Welcome.vue"

import User from "../views/user/user.vue"
Vue.use(VueRouter);

const routes = [
  { path: "/", redirect: "/login" },

  { path: "/login", component: Login },

  { path: "/home", component: Home,
  redirect:"/welcome",
  children:[
    {path:"/welcome",component:Welcome},
    {path:'/users',component:User}
  ]

}
];

const router = new VueRouter({
  routes
});
//全局前置shouwei 只要通过路由进行组件切换,都会经过这个函数
// beforeEach:导航守卫
// to:将要访问的页面路径
// from:从那个页面路径跳转过来的
// next() 放行的函数  next(''/login)  强制跳转
router.beforeEach((to, from, next) => {
  // 只要是去登录组件 ,都可以放行
  if (to.path === "/login") return next();
  //获取token
  const token = window.sessionStorage.getItem("token");
  // 如果没有token 都去login组件
  if (!token) return next("/login");
  //否则放行
  next();
});

export default router;
